"""
系统管理API视图
"""
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.utils import timezone
from datetime import timedelta

from .models import Permission, RolePermission, LoginLog
from .serializers import (
    UserManageSerializer, UserCreateSerializer, UserUpdateSerializer,
    PermissionSerializer, RolePermissionSerializer, LoginLogSerializer
)
from .permissions import IsAdminUser

User = get_user_model()


class StandardResultsSetPagination(PageNumberPagination):
    """标准分页"""
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 100


class UserManageViewSet(viewsets.ModelViewSet):
    """用户管理ViewSet"""
    
    queryset = User.objects.all().order_by('-created_at')
    permission_classes = [permissions.IsAuthenticated, IsAdminUser]
    pagination_class = StandardResultsSetPagination
    
    def get_serializer_class(self):
        if self.action == 'create':
            return UserCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return UserUpdateSerializer
        return UserManageSerializer
    
    def get_queryset(self):
        queryset = User.objects.all().order_by('-created_at')
        
        # 搜索过滤
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(username__icontains=search) |
                Q(first_name__icontains=search) |
                Q(last_name__icontains=search) |
                Q(email__icontains=search) |
                Q(phone__icontains=search)
            )
        
        # 角色过滤
        role = self.request.query_params.get('role', None)
        if role:
            queryset = queryset.filter(role=role)

        # 多角色过滤（用于前端只显示管理员和老师）
        role_filter = self.request.query_params.get('role_filter', None)
        if role_filter:
            roles = role_filter.split(',')
            queryset = queryset.filter(role__in=roles)

        # 状态过滤
        is_active = self.request.query_params.get('is_active', None)
        if is_active is not None:
            queryset = queryset.filter(is_active=is_active.lower() == 'true')

        return queryset
    
    def create(self, request, *args, **kwargs):
        """创建用户"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 检查用户名是否已存在
        username = serializer.validated_data['username']
        if User.objects.filter(username=username).exists():
            return Response({
                'error': '用户名已存在'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查邮箱是否已存在
        email = serializer.validated_data.get('email')
        if email and User.objects.filter(email=email).exists():
            return Response({
                'error': '邮箱已存在'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        user = serializer.save()
        return Response(
            UserManageSerializer(user).data,
            status=status.HTTP_201_CREATED
        )
    
    @action(detail=True, methods=['post'])
    def reset_password(self, request, pk=None):
        """重置用户密码"""
        user = self.get_object()
        new_password = request.data.get('password', '123456')
        
        user.set_password(new_password)
        user.save()
        
        return Response({
            'message': '密码重置成功',
            'new_password': new_password
        })
    
    @action(detail=True, methods=['post'])
    def toggle_active(self, request, pk=None):
        """切换用户激活状态"""
        user = self.get_object()
        user.is_active = not user.is_active
        user.save()
        
        return Response({
            'message': f"用户已{'激活' if user.is_active else '禁用'}",
            'is_active': user.is_active
        })
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """用户统计信息"""
        total_users = User.objects.count()
        active_users = User.objects.filter(is_active=True).count()
        
        # 按角色统计
        role_stats = {}
        for role_code, role_name in User.ROLE_CHOICES:
            role_stats[role_code] = {
                'name': role_name,
                'count': User.objects.filter(role=role_code).count()
            }
        
        # 最近7天新增用户
        seven_days_ago = timezone.now() - timedelta(days=7)
        recent_users = User.objects.filter(created_at__gte=seven_days_ago).count()
        
        return Response({
            'total_users': total_users,
            'active_users': active_users,
            'inactive_users': total_users - active_users,
            'role_statistics': role_stats,
            'recent_users': recent_users
        })


class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
    """权限管理ViewSet（只读）"""
    
    queryset = Permission.objects.all().order_by('module', 'name')
    serializer_class = PermissionSerializer
    permission_classes = [permissions.IsAuthenticated, IsAdminUser]
    pagination_class = StandardResultsSetPagination
    
    def get_queryset(self):
        queryset = Permission.objects.all().order_by('module', 'name')
        
        # 模块过滤
        module = self.request.query_params.get('module', None)
        if module:
            queryset = queryset.filter(module=module)
        
        # 搜索过滤
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) |
                Q(codename__icontains=search) |
                Q(description__icontains=search)
            )
        
        return queryset
    
    @action(detail=False, methods=['get'])
    def modules(self, request):
        """获取所有模块"""
        modules = Permission.objects.values_list('module', flat=True).distinct()
        return Response(list(modules))


class RolePermissionViewSet(viewsets.ModelViewSet):
    """角色权限管理ViewSet"""
    
    queryset = RolePermission.objects.all().order_by('role', 'permission__module')
    serializer_class = RolePermissionSerializer
    permission_classes = [permissions.IsAuthenticated, IsAdminUser]
    
    def get_queryset(self):
        queryset = RolePermission.objects.all().order_by('role', 'permission__module')
        
        # 角色过滤
        role = self.request.query_params.get('role', None)
        if role:
            queryset = queryset.filter(role=role)
        
        return queryset
    
    @action(detail=False, methods=['get'])
    def by_role(self, request):
        """按角色获取权限"""
        role_permissions = {}
        
        for role_code, role_name in User.ROLE_CHOICES:
            permissions = RolePermission.objects.filter(role=role_code).select_related('permission')
            role_permissions[role_code] = {
                'name': role_name,
                'permissions': [
                    {
                        'id': rp.permission.id,
                        'name': rp.permission.name,
                        'codename': rp.permission.codename,
                        'module': rp.permission.module
                    }
                    for rp in permissions
                ]
            }
        
        return Response(role_permissions)
    
    @action(detail=False, methods=['post'])
    def batch_update(self, request):
        """批量更新角色权限"""
        role = request.data.get('role')
        permission_ids = request.data.get('permission_ids', [])
        
        if not role:
            return Response({
                'error': '角色参数必填'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 删除该角色的所有权限
        RolePermission.objects.filter(role=role).delete()
        
        # 添加新的权限
        for permission_id in permission_ids:
            try:
                permission = Permission.objects.get(id=permission_id)
                RolePermission.objects.create(role=role, permission=permission)
            except Permission.DoesNotExist:
                continue
        
        return Response({
            'message': f'{dict(User.ROLE_CHOICES)[role]}权限更新成功'
        })


class LoginLogViewSet(viewsets.ReadOnlyModelViewSet):
    """登录日志ViewSet（只读）"""
    
    queryset = LoginLog.objects.all().order_by('-login_time')
    serializer_class = LoginLogSerializer
    permission_classes = [permissions.IsAuthenticated, IsAdminUser]
    pagination_class = StandardResultsSetPagination
    
    def get_queryset(self):
        queryset = LoginLog.objects.all().order_by('-login_time')
        
        # 用户过滤
        user_id = self.request.query_params.get('user_id', None)
        if user_id:
            queryset = queryset.filter(user_id=user_id)
        
        # 时间范围过滤
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        
        if start_date:
            queryset = queryset.filter(login_time__gte=start_date)
        if end_date:
            queryset = queryset.filter(login_time__lte=end_date)
        
        # IP过滤
        ip_address = self.request.query_params.get('ip_address', None)
        if ip_address:
            queryset = queryset.filter(ip_address__icontains=ip_address)
        
        return queryset
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """登录统计"""
        from django.db.models import Count, Avg, Q
        from datetime import datetime, timedelta

        # 今日登录次数
        today = timezone.now().date()
        today_logins = LoginLog.objects.filter(login_time__date=today).count()

        # 最近7天登录统计
        seven_days_ago = timezone.now() - timedelta(days=7)
        recent_logins = LoginLog.objects.filter(login_time__gte=seven_days_ago)

        # 按日期分组统计
        daily_stats = {}
        for i in range(7):
            date = (timezone.now() - timedelta(days=i)).date()
            count = recent_logins.filter(login_time__date=date).count()
            daily_stats[str(date)] = count

        # 最活跃用户（最近7天）
        active_users = (
            LoginLog.objects
            .filter(login_time__gte=seven_days_ago)
            .values('user__username', 'user__first_name', 'user__last_name', 'user__role')
            .annotate(login_count=Count('id'))
            .order_by('-login_count')[:10]
        )

        # 在线用户统计
        online_users = LoginLog.objects.filter(logout_time__isnull=True).count()

        # 总登录次数
        total_logins = LoginLog.objects.count()

        # 平均会话时长（已退出的会话）- SQLite兼容版本
        completed_sessions = LoginLog.objects.filter(logout_time__isnull=False)
        total_duration = 0
        session_count = 0

        for log in completed_sessions:
            if log.logout_time and log.login_time:
                duration = (log.logout_time - log.login_time).total_seconds()
                total_duration += duration
                session_count += 1

        avg_session_duration = total_duration / session_count if session_count > 0 else 0

        # 失败登录统计
        failed_logins_today = LoginLog.objects.filter(
            login_time__date=today,
            is_success=False
        ).count()

        return Response({
            'today_logins': today_logins,
            'daily_statistics': daily_stats,
            'active_users': list(active_users),
            'online_users': online_users,
            'total_logins': total_logins,
            'failed_logins_today': failed_logins_today,
            'avg_session_duration': avg_session_duration  # 现在是秒数
        })

    @action(detail=False, methods=['get'])
    def export(self, request):
        """导出登录日志"""
        import csv
        from django.http import HttpResponse
        from io import StringIO

        # 获取查询参数
        queryset = self.get_queryset()

        # 创建CSV响应
        response = HttpResponse(content_type='text/csv; charset=utf-8')
        response['Content-Disposition'] = 'attachment; filename="login_logs.csv"'

        # 添加BOM以支持Excel中文显示
        response.write('\ufeff')

        writer = csv.writer(response)

        # 写入表头
        writer.writerow([
            '用户名', '姓名', '角色', 'IP地址', '浏览器',
            '登录时间', '退出时间', '在线时长(分钟)', '状态', '是否成功'
        ])

        # 写入数据
        for log in queryset.select_related('user'):
            duration = ''
            if log.logout_time:
                duration_seconds = (log.logout_time - log.login_time).total_seconds()
                duration = f"{int(duration_seconds // 60)}"
            elif log.login_time:
                duration_seconds = (timezone.now() - log.login_time).total_seconds()
                duration = f"{int(duration_seconds // 60)} (在线)"

            writer.writerow([
                log.user.username,
                f"{log.user.first_name} {log.user.last_name}".strip(),
                log.user.get_role_display(),
                log.ip_address,
                log.user_agent[:50] + '...' if len(log.user_agent) > 50 else log.user_agent,
                log.login_time.strftime('%Y-%m-%d %H:%M:%S'),
                log.logout_time.strftime('%Y-%m-%d %H:%M:%S') if log.logout_time else '-',
                duration,
                '已退出' if log.logout_time else '在线',
                '成功' if log.is_success else '失败'
            ])

        return response


class TeacherViewSet(viewsets.ModelViewSet):
    """教师管理ViewSet"""
    serializer_class = UserManageSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        """获取教师列表"""
        return User.objects.filter(role='teacher', is_active=True).order_by('-date_joined')

    def get_serializer_class(self):
        """根据操作类型选择序列化器"""
        if self.action == 'create':
            return UserCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return UserUpdateSerializer
        return UserManageSerializer

    def create(self, request, *args, **kwargs):
        """创建教师"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 设置为教师角色
        validated_data = serializer.validated_data
        validated_data['role'] = 'teacher'

        user = serializer.save()

        return Response(
            UserManageSerializer(user).data,
            status=status.HTTP_201_CREATED
        )

    @action(detail=False, methods=['get'], url_path='simple-list')
    def simple_list(self, request):
        """获取简化的教师列表（用于下拉框）"""
        teachers = self.get_queryset().values('id', 'username', 'first_name', 'last_name')
        return Response(list(teachers))
